package com.ljd.controller;


import com.ljd.entity.Book;
import com.ljd.entity.Borrow;
import com.ljd.entity.Reader;
import com.ljd.service.BookService;
import com.ljd.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/book")
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Reader reader = (Reader) session.getAttribute("reader");
        String method = req.getParameter("method");
        if (method == null) {
            method = "findAll";
        }
        //流程控制
        switch (method) {
            case "findAll":
                //当前页数
                String pageStr = req.getParameter("page");
                Integer page = Integer.parseInt(pageStr);
                //获取该页图书
                List<Book> list = bookService.findAllBooks(page);
                req.setAttribute("list", list);
                req.setAttribute("dataPerPage", 5);
                req.setAttribute("currentPage", page);
                req.setAttribute("pages", bookService.getPagesCount());
                req.getRequestDispatcher("index.jsp").forward(req, resp);
                break;

            case "addBorrow":
                //添加借阅
                String bookidStr = req.getParameter("bookid");
                Integer bookid = Integer.parseInt(bookidStr);
                //添加借书请求
                bookService.addBorrow(bookid, reader.getId());
                resp.sendRedirect("/book?method=findAllBorrow&page=1");
                break;

            case "findAllBorrow":
                pageStr = req.getParameter("page");
                page = Integer.parseInt(pageStr);
                //展示当前用户的所有借书记录
                List<Borrow> borrowList = bookService.findAllBorrowByReaderId(page, reader.getId());
                req.setAttribute("borrowList",borrowList);
                req.setAttribute("dataPerPage", 5);
                req.setAttribute("currentPage", page);
                req.setAttribute("pages", bookService.getBorrowPagesCount(reader.getId()));
                req.getRequestDispatcher("borrow.jsp").forward(req, resp);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
